<template>
  <el-container class="flex-container" v-loading="pageLoading">
    <el-aside width="33%" style="padding: 20px;;border: 1px solid rgb(238, 238, 238)">
      <el-tree :data="treeData" node-key="id" highlight-current default-expand-all @node-click="handleNodeClick"
        :expand-on-click-node="false">
        <template #default="{ node }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span>
              <el-button type="text" style="color:green" size="mini" @click="(e) => appendSibling(node, e)">
                新增同级
              </el-button>
              <el-button type="text" style="color:green" size="mini" @click="(e) => appendChild(node, e)">
                新增下级
              </el-button>
              <el-button type="text" style="color:red" size="mini" @click="(e) => removeNode(node, e)">
                删除
              </el-button>
            </span>
          </span>
        </template>
      </el-tree>
    </el-aside>

    <el-main style="width: 67%; border: 1px solid rgb(238, 238, 238);padding: 0%;">
      <div class="right-panel">
        <div v-if="!selectedNode" class="node-prompt">
          请点击节点进行编辑
        </div>
        <div v-else>
          <!-- 异常类型信息 -->
          <el-tabs v-model="activeTab">
            <el-tab-pane :label="tabName" name="main">
              <el-form :model="abnormalForm" label-width="120px"  :rules="formRules" ref="form">
                <el-form-item v-show="abnormalForm.ParentName" label="父节点">
                  <el-input disabled clearable v-model="abnormalForm.ParentName" placeholder="父节点" />
                </el-form-item>
                <el-form-item label="异常类型编码" prop="AbnormalCode">
                  <el-input clearable v-model="abnormalForm.AbnormalCode" placeholder="请输入异常类型编码" />
                </el-form-item>

                <el-form-item label="异常类型名称" prop="AbnormalName">
                  <el-input clearable v-model="abnormalForm.AbnormalName" placeholder="请输入异常类型名称" />
                </el-form-item>
                <el-form-item label="优先级" prop="Priority">
                  <el-select v-model="abnormalForm.Priority" placeholder="请选择优先级" style="width: 100%">
                    <el-option v-for="item in priorityList" :key="item.key" :label="item.value" :value="item.key" />
                  </el-select>
                </el-form-item>
                <el-form-item label="所属部门" v-if="abnormalForm.ParentId == null">
                  <el-cascader :options="deptList" v-model="abnormalForm.Depts" :props="props" style="width: 100%;"
                    clearable></el-cascader>
                </el-form-item>

                <el-form-item label="负责人部门">
                  <el-cascader :options="deptList" v-model="abnormalForm.ResponsibleDept" :props="props1"
                    style="width: 100%;" clearable></el-cascader>
                </el-form-item>

                <el-form-item label="负责人">
                  <el-select clearable v-model="abnormalForm.ResponsiblePersons" filterable multiple
                    placeholder="请选择负责人" style="width: 100%">
                    <el-option v-for="item in Sys_UserList" :key="item.key" :label="item.value" :value="item.key" />
                  </el-select>
                </el-form-item>
              </el-form>

              <!-- 超时提示时间配置 -->
              <div class="timeout-container">
                <el-table :data="timeoutConfig" border style="width: 100%; height: 250px"
                  :cell-style="{ textAlign: 'center' }" class="scrollable-table">
                  <el-table-column label="序号" align="center" width="60">
                    <template #default="{ $index }">
                      <div style="display: flex; justify-content: center;">
                        <div class="time-inputs" style="display: flex; align-items: center; gap: 8px;">
                          <span class="time-unit">{{ $index + 1 }}</span>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="岗位" align="center">
                    <template #default="{ row }">
                      <el-select filterable v-model="row.position" placeholder="请选择岗位" style="width: 100%;">
                        <el-option v-for="item in APS_PostList" :key="item.key" :label="item.value" :value="item.key" />
                      </el-select>
                    </template>
                  </el-table-column>

                  <el-table-column label="超时提示时间" align="center" width="400">
                    <template #default="{ row }">
                      <div style="display: flex; justify-content: center;">
                        <div class="time-inputs" style="display: flex; align-items: center; gap: 8px;">
                          <el-input-number v-model="row.minutes" :min="0" label="分钟" />
                          <span class="time-unit">分钟</span>
                        </div>
                      </div>
                    </template>
                  </el-table-column>

                  <el-table-column label="操作" align="center" width="100">
                    <template #default="{ $index }">
                      <div class="flex">
                        <div class="table-actions">
                          <el-link type="danger" @click="removeTimeoutConfig($index)">删除</el-link>
                        </div>
                        <div class="table-actions ml-10" v-if="timeoutConfig?.length == $index + 1">
                          <el-link type="success" @click="addTimeoutConfig">新增</el-link>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <div class="action-buttons">
                <el-button type="primary" size="medium" @click="Save">保存</el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import { divide, forEach } from 'lodash';

export default {
  name: 'AdsAbnormalType',
  data() {
    return {
      loading: false,
      treeData: [],
      Sys_UserList: [],
      APS_PostList: [],
      deptList: [],
      priorityList: [],
      formRules: {
        Priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
        AbnormalName: [{ required: true, message: '请输入异常名称', trigger: 'change' }],
        AbnormalCode: [{ required: true, message: '请输入异常编码', trigger: 'change' }],
      },
      props: { multiple: true },
      props1: {
        // multiple: true,
        checkStrictly: true,
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      selectedNode: false,
      tabName: '新增',
      activeTab: 'main', // 默认激活第一个 Tab
      abnormalForm: {
        AbnormalId: 0,
        ParentId: '',
        ParentName: '',
        AbnormalCode: '',
        AbnormalName: '',
        Depts: [],
        ResponsibleDept: [],
        ResponsiblePersons: []
      },

      timeoutConfig: [{
        position: '',
        minutes: 0
      }],

      positionOptions: [],
      departmentOptions: [],
      responsiblePersonOptions: []
    }
  },
  watch: {
    'abnormalForm.ResponsibleDept': {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.deptListChange(newVal);
        }
      },
      immediate: true, // 立即触发一次
    },
  },
  methods: {
    initDetail(parentId) {
      //基础信息初始化
      this.abnormalForm = {
        AbnormalId: 0,
        AbnormalCode: '',
        AbnormalName: '',
        Depts: [],
        ResponsibleDept: [],
        ResponsiblePersons: []
      }
      if (parentId) {
        this.abnormalForm.ParentId = parentId
        //获取树状结构的具体名称
        this.abnormalForm.ParentName = this.findLabelByAbnormalTypeId(this.treeData, parentId)
      }
      //超时列表初始化
      this.timeoutConfig = [{
        position: '',
        minutes: 0
      }]
    },
    //扁平化树形数据
    flattenTreeData(treeData) {
      return treeData?.reduce((acc, item) => {
        acc.push(item); // 添加当前节点
        if (item.children && item.children.length > 0) {
          acc.push(...this.flattenTreeData(item.children)); // 递归添加子节点
        }
        return acc;
      }, []);
    },

    //根据 AbnormalTypeId 查找 label
    findLabelByAbnormalTypeId(treeData, abnormalTypeId) {
      const flatData = this.flattenTreeData(treeData); // 扁平化树形数据
      console.log(flatData)
      const foundItem = flatData.find(item => item.id === abnormalTypeId); // 查找匹配的节点
      return foundItem ? foundItem.label : null; // 返回 label 或 null
    },
    initData() {
      this.http
        .post('api/Sys_Dictionary/GetVueDictionary', [
          "Sys_User",
          "APS_Post",
          "部门级联",
          "Ads_Abnormal_Priority",
        ])
        .then((r) => {
          r.forEach(t => {
            if (t.DictionaryNo == 'Sys_User') {
              this.Sys_UserList = t.data
            }
            if (t.DictionaryNo == 'APS_Post') {
              this.APS_PostList = t.data
            }
            if (t.DictionaryNo == 'Ads_Abnormal_Priority') {
              this.priorityList = t.data
            }
            if (t.DictionaryNo == '部门级联') {
              this.deptList = this.transformData(t.data)
            }
          })
        })
      this.fetchTreeData()
    },

    transformData(data) {
      const map = new Map();
      const result = [];

      data.forEach(item => {
        map.set(item.id, { ...item, children: [] });
      });

      data.forEach(item => {
        if (item.parentId === null) {
          result.push(map.get(item.id));
        } else {
          const parent = map.get(item.parentId);
          if (parent) {
            parent.children.push(map.get(item.id));
          }
        }
      });

      const mapToCascaderFormat = (node) => {
        return {
          label: node.value,
          value: node.id,
          children: node.children.length > 0 ? node.children.map(mapToCascaderFormat) : undefined,
        };
      };

      return result.map(mapToCascaderFormat);
    },

    fetchTreeData() {
      this.loading = true;
      this.http.get('/api/Ads_AbnormalType/GetTree', null, {})
        .then(response => {
          console.log(response)
          if (response.length > 0) {
            this.treeData = this.transformTreeData(response);
          } else {
            this.selectedNode = true
            this.tabName = '新增'
          }
        })
        .catch(error => {
          console.error('获取异常类型数据失败:', error);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    transformTreeData(items) {
      return items.map(item => ({
        parentId: item.ParentId,
        id: item.AbnormalTypeId,
        label: `${item.AbnormalCode} - ${item.AbnormalName}`,
        children: item.Children ? this.transformTreeData(item.Children) : [],
        rawData: item
      }));
    },
    //获取当前节点的详细信息
    handleNodeClick(data) {
      console.log('修改', data)
      this.tabName = data.label
      this.initDetail(data.ParentId)
      this.selectedNode = true;
      this.loading = true;

      this.http.get('/api/Ads_AbnormalType/GetDetail', { AbnormalTypeId: data.id })
        .then(response => {
          if (response) {
            this.abnormalForm = {
              ...response,
              Priority: String(response.Priority),
              ParentName: this.findLabelByAbnormalTypeId(this.treeData, response.ParentId),
              Depts: response.Depts ? this.stringToJson(response.Depts) : [],
              ResponsibleDept: response.ResponsibleDept ? this.stringToJson(response.ResponsibleDept) : [],
              ResponsiblePersons: response.ResponsiblePersons ? this.stringToJson(response.ResponsiblePersons) : []
            };

            this.timeoutConfig = response.TimeoutAlerts.map(t => {
              return {
                position: t.Post || '', // 如果 t.Post 不存在，默认为空字符串
                minutes: t.TimeoutAlertMinutes || 0, // 如果 time.minutes 不存在，默认为 0
              };
            })

            if (!this.timeoutConfig) {
              this.timeoutConfig = [{
                position: '',
                minutes: 0
              }]
            } else if (this.timeoutConfig.length == 0) {
              this.timeoutConfig = [{
                position: '',
                minutes: 0
              }]
            }
            console.log('done')
          }
        })
        .catch(error => {
          console.error('获取异常类型详情数据失败:', error);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    stringToJson(str) {
      try {
        return JSON.parse(str);
      } catch (error) {
        return [];
      }
    },
    jsonToString(json) {
      try {
        return JSON.stringify(json);
      } catch (error) {
        return '';
      }
    },
    addTimeoutConfig() {
      this.timeoutConfig.push({
        position: '',
        minutes: 0
      });
    },
    removeTimeoutConfig(index) {
      if (this.timeoutConfig?.length == 1) {
        this.timeoutConfig = [{
          position: '',
          minutes: 0
        }]
      } else {
        this.timeoutConfig.splice(index, 1);
      }
    },

    Save() {
      //检查数据
      var isOk = true
      if (
        (!this.abnormalForm.ResponsibleDept || this.abnormalForm.ResponsibleDept.length === 0) &&
        (!this.abnormalForm.ResponsiblePersons || this.abnormalForm.ResponsiblePersons.length === 0)
      ) {
        this.$message.info("负责部门或者负责人必须要有一个");
        return;
      }
      const requestData = {
        AbnormalTypeId: this.abnormalForm.AbnormalTypeId,
        ParentId: this.abnormalForm.ParentId,
        AbnormalCode: this.abnormalForm.AbnormalCode,
        AbnormalName: this.abnormalForm.AbnormalName,
        Priority: this.abnormalForm.Priority,
        Depts: this.jsonToString(this.abnormalForm.Depts==undefined?[]:this.abnormalForm.Depts),
        ResponsibleDept: this.jsonToString(this.abnormalForm.ResponsibleDept==undefined?[]:this.abnormalForm.ResponsibleDept),
        ResponsiblePersons: this.jsonToString(this.abnormalForm.ResponsiblePersons==undefined?[]:this.abnormalForm.ResponsiblePersons),
      };
      //转换超时提醒的总分钟数
      requestData.TimeoutAlerts = this.timeoutConfig.map(t => {
        return {
          AbnormalTypeId: this.abnormalForm.AbnormalTypeId,
          TimeoutAlertMinutes: t.minutes ? t.minutes : 0,
          Post: t.position ? t.position : ''
        };
      })
      if (requestData.TimeoutAlerts?.length > 1) {
        requestData.TimeoutAlerts.forEach((t, index) => {
          if (t.Post === '') {
            this.$message.info("第" + (index + 1) + "行岗位不能为空，请核对")
            isOk = false
          }
          if (t.TimeoutAlertMinutes === 0) {
            this.$message.info("第" + (index + 1) + "行时间应该大于0，请核对")
            isOk = false
          }
        })
      }
      if (!isOk) {
        return
      }
      this.$refs.form.validate(async (valid) => {
        if (valid) {//转派和退回时可不校验必填框
          this.http.post('/api/Ads_AbnormalType/AddOrUpdate', requestData).then(r => {
            if (r) {
              this.$message.success('保存成功')
              this.fetchTreeData()
            }
          }).catch(error => {

          })
        } else {
          this.$message.warning('请填写完整表单');
        }
      });
    },
    deptListChange(value) {
      this.Sys_UserList = []
      var lastElement = ''
      if (value !== undefined) {
        lastElement = value[value.length - 1]
      }
      this.http.get('/api/Ads_AbnormalType/GetUsersByDept', { deptId: lastElement }).then(r => {
        if (r.length > 0) {
          this.Sys_UserList = r
          //筛选只有当前用户列表的数据并提示
          if (this.abnormalForm.ResponsiblePersons.length > 0) {
            var isDiff = true
            this.abnormalForm.ResponsiblePersons.forEach((item, index) => {
              var person = this.Sys_UserList.find(t => t.key == item);
              if (!person) {
                isDiff = false;
              }
            })
            if (!isDiff) {
              this.abnormalForm.ResponsiblePersons = []
              this.$message.info("部分负责人不存在当前部门，请重新添加")
            }
          }
        } else {
          this.abnormalForm.ResponsiblePersons = []
          this.$message.info("当前岗位未绑定用户，请核对！")
        }
      }).catch(error => {
        this.$message.error('保存失败', error)
      })
    },
    checkData() {

    },
    appendSibling(node, event) {
      this.tabName = '新增'
      event.stopPropagation(); // 阻止事件冒泡
      this.initDetail(node.data.parentId)
      this.selectedNode = true
    },

    appendChild(node, event) {
      this.tabName = '新增'
      event.stopPropagation(); // 阻止事件冒泡
      this.initDetail(node.data.id)
      this.selectedNode = true
    },

    findNodeById(nodes, id) {
      for (const node of nodes) {
        if (node.id === id) return node;
        if (node.children) {
          const found = this.findNodeById(node.children, id);
          if (found) return found;
        }
      }
      return null;
    },
    removeNode(node, event) {
      event.stopPropagation(); // 阻止事件冒泡
      this.selectedNode = false
      this.$confirm("确定要删除该节点及以下数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.http.post('/api/Ads_AbnormalType/del', [node.data.id]).then(r => {
            this.fetchTreeData()
          }).catch(error => {
          })
        })
        .catch(() => { });
    },
    findNewNodes(nodes) {
      let newNodes = [];
      for (const node of nodes) {
        if (node.isNew) {
          newNodes.push(node);
        }
        if (node.children) {
          newNodes = newNodes.concat(this.findNewNodes(node.children));
        }
      }
      return newNodes;
    },
  },

  mounted() {
    this.initData();
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-tabs__header.is-top {
  border-left: 1px solid #fff !important;
}

.node-prompt {
  color: #999;
  font-size: 18px;
  text-align: center;
  margin-top: 100px;
}

.flex-container {
  display: flex;
  height: 80vh;
}

.right-panel {
  padding: 0%;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: right;
  gap: 10px;
  flex-wrap: wrap;
  padding-top: 20px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.timeout-container {
  margin-top: 20px;
}

.timeout-header {
  overflow: hidden;
}
</style>
